@extends('layout.master')

@section('content-header')
    <h1>Lingkungan</h1>
    <ol class="breadcrumb">
        <li><a href="/"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li class="active"><i class="fa fa-cog"></i> Pengaturan</li>
        <li class="active"><i class="fa fa-building"></i>Lingkungan</li>
    </ol>
@stop

@section('content')

<div class="row">
    <div class="col-xs-12">

        <div class="box box-midnight">
            <div class="box-header">

            </div><!-- /.box-header -->
            <div class="box-body">
                <div class="output">

                </div>

                @if(isset($message))
                <div class="callout callout-warning animated fadeIn">
                    <h4>Harap lengkapi data lingkungan!</h4>
                    <p>Data lingkungan digunakan sebagai profil lingkungan dimana sistem ini dioperasikan.</p>
                </div>
                @endif

                <form class="form-horizontal" role="form" method="post" id="frmInput">                
                <h4 class="header-form">Informasi Umum</h4>
                    <div class="form-group">
                        <label for="nama" class="col-sm-2 control-label">Nama</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="nama" name="nama" placeholder="Nama Lingkungan" value="{{ isset($nama) ? $nama : '';  }}">
                        </div>
                        <label for="telp_ling" class="col-sm-2 control-label">Telepon Lingkungan</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="telp_ling" name="telp_ling" placeholder="Telepon Lingkungan" value="{{ isset($telp_ling) ? $telp_ling : '';  }}">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="kepala_desa" class="col-sm-2 control-label">Kepala Desa</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="kepala_desa" name="kepala_desa" placeholder="Kepala Desa" value="{{ isset($kepala_desa) ? $kepala_desa : '';  }}">
                        </div>                        
                        <label for="telp_lurah" class="col-sm-2 control-label">Telepon Kelurahan</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="telp_lurah" name="telp_lurah" placeholder="Telepon Kelurahan" value="{{ isset($telp_lurah) ? $telp_lurah : '';  }}">
                        </div>                                    
                    </div>
                    <div class="form-group">
                        <label for="kepala_lingkungan" class="col-sm-2 control-label">Kepala Lingkungan</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="kepala_lingkungan" name="kepala_lingkungan" placeholder="Kepala Lingkungan" value="{{ isset($kepala_lingkungan) ? $kepala_lingkungan : '';  }}">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="provinsi_id" class="col-sm-2 control-label">Provinsi</label>
                        <div class="col-sm-10">
                            <select name="provinsi_id" id="provinsi_id" class="form-control">
                                <option value="">- - Pilih Provinsi - -</option>
                                @foreach($provinsis as $provinsi)
                                    <option value="{{ $provinsi->id }}" {{ (isset($provinsi_id) && ($provinsi_id == $provinsi->id)) ? 'selected' : '' }}>{{ $provinsi->nama }}</option>
                                @endforeach
                            </select>                            
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="kabupaten_id" class="col-sm-2 control-label">Kabupaten</label>
                        <div class="col-sm-10">
                            <select name="kabupaten_id" id="kabupaten_id" class="form-control">
                                <option value="">- - Pilih Kabupaten - -</option>                                
                            </select>                            
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="kecamatan_id" class="col-sm-2 control-label">Kecamatan</label>
                        <div class="col-sm-10">
                            <select name="kecamatan_id" id="kecamatan_id" class="form-control">
                                <option value="">- - Pilih Kecamatan - -</option>                                
                            </select>                            
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="kelurahan_id" class="col-sm-2 control-label">Kelurahan</label>
                        <div class="col-sm-10">
                            <select name="kelurahan_id" id="kelurahan_id" class="form-control">
                                <option value="">- - Pilih Kelurahan - -</option>                                
                            </select>                            
                        </div>
                    </div>                                                                                
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Lokasi</label>
                        <div class="col-sm-10">
                            <div id="map_canvas"></div>
                            <input type="text" id="latFld" class="hidden" value="{{ isset($lat_lng[0]) ? $lat_lng[0] : '-8.65000';  }}">
                            <input type="text" id="lngFld" class="hidden" value="{{ isset($lat_lng[1]) ? $lat_lng[1] : '115.21667';  }}">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="keterangan" class="col-sm-2 control-label">Keterangan</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" name="keterangan" id="keterangan" cols="30" rows="5" placeholder="Keterangan">{{ isset($keterangan) ? $keterangan : '';  }}</textarea>
                        </div>
                    </div>
                    
                    <h4 class="header-form">Logo Lingkungan</h4>
                    <div class="form-group">
                        <div class="col-sm-10 col-sm-offset-2">
                            <div class="pull-left" style="margin-right: 20px; ">
                                <div class="img-holder">
                                    <span class="helper"></span>
                                    
                                    @if(isset($logo_kop_surat) && $logo_kop_surat != "" && File::exists(public_path() . Lingkungan::$logoPath . $logo_kop_surat))
                                        <img src="{{ URL::asset(Lingkungan::$logoPath . $logo_kop_surat) }}" class="img-logo" alt="Logo Kop Surat" width="150" data-filename="{{ $logo_kop_surat }}">
                                    @else
                                        <img src="{{ URL::asset('/') }}img/img-not-found.jpg" class="img-logo" alt="Logo Kop Surat" width="150" data-filename="">
                                    @endif
                                </div>                                
                            </div>
                            <input type="file" id="logo" name="logo" class="hidden">
                            <a href="#" class="btn btn-danger btn-upload-logo"><i class="fa fa-folder-open"></i> Logo Lingkungan</a>
                        </div>
                    </div>
                    
                    <h4 class="header-form">Tanda Tangan</h4>
                    <div class="form-group">
                        <label for="telp_lurah" class="col-sm-2 control-label"></label>
                        <div class="col-sm-10">
                            <label class="checkbox-inline alpha">
                                <input type="checkbox" id="using_kepling" value="1" {{ (isset($using_kepling) && $using_kepling == 1) ? 'checked' : '' }}> Kepala Lingkungan
                            </label>
                            <label class="checkbox-inline">
                                <input type="checkbox" id="using_keldat" value="1" {{ (isset($using_keldat) && $using_keldat == 1) ? 'checked' : '' }}> Kelian Adat
                            </label>  
                        </div>
                    </div>
                    <div class="form-group">                        
                        <div class="col-sm-10 col-sm-offset-2">
                            <div class="pull-left" style="margin-right: 20px; ">
                                <div class="img-holder">                                    
                                    <span class="helper"></span>

                                    @if(isset($ttd_kepling) && $ttd_kepling != "" && File::exists(public_path() . Lingkungan::$ttdPath . $ttd_kepling))
                                        <img src="{{ URL::asset(Lingkungan::$ttdPath . $ttd_kepling) }}" class="img-ttd-kepling" alt="TTD Kepala Lingkungan" width="150" data-filename="{{ $ttd_kepling }}">
                                    @else
                                        <img src="{{ URL::asset('/') }}img/img-not-found.jpg" class="img-ttd-kepling" alt="Logo TTD Kepala Lingkungan" width="150" data-filename="">
                                    @endif

                                </div>
                            </div>
                            <input type="file" id="ttd_kepling" name="ttd_kepling" class="hidden">
                            <a href="#" class="btn btn-danger btn-upload-ttd-kepling"><i class="fa fa-folder-open"></i> TTD Kepala Lingkungan</a>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10 col-sm-offset-2">
                                <div class="pull-left" style="margin-right: 20px; ">
                                <div class="img-holder">
                                    <span class="helper"></span>

                                    @if(isset($ttd_keldat) && $ttd_keldat != "" && File::exists(public_path() . Lingkungan::$ttdPath . $ttd_keldat))
                                        <img src="{{ URL::asset(Lingkungan::$ttdPath . $ttd_keldat) }}" class="img-ttd-keldat" alt="TTD Kepala Dat" width="150" data-filename="{{ $ttd_keldat }}">
                                    @else
                                        <img src="{{ URL::asset('/') }}img/img-not-found.jpg" class="img-ttd-keldat" alt="Logo TTD Kepala Dat" width="150" data-filename="">
                                    @endif

                                </div>                                
                            </div>
                            <input type="file" id="ttd_keldat" name="ttd_keldat" class="hidden">
                            <a href="#" class="btn btn-danger btn-upload-ttd-keldat"><i class="fa fa-folder-open"></i> TTD Kelian Adat</a>
                        </div>
                    </div>
                    <h4 class="header-form">Kipem Provinsi & Luar Provinsi</h4>                    
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Lama Berlaku Provinsi</label>
                        <div class="col-sm-4">
                            <input type="number" name="lama_prov" id="lama_prov" class="form-control" placeholder="Lama Berlaku Provinsi" value="{{ isset($lama_prov) ? $lama_prov : '';  }}">
                        </div>
                        <label class="col-sm-2 control-label">Lama Berlaku Luar Provinsi</label>
                        <div class="col-sm-4">
                            <input type="number" name="lama_luar_prov" id="lama_luar_prov" class="form-control" placeholder="Lama Berlaku Luar Provinsi" value="{{ isset($lama_luar_prov) ? $lama_luar_prov : '';  }}">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Satuan Berlaku Provinsi</label>
                        <div class="col-sm-4">
                            <select name="satuan_prov" id="satuan_prov" class="form-control">
                                <option value="">- - Pilih Satuan Berlaku - -</option>
                                <option value="1" {{ (isset($satuan_prov) && ($satuan_prov == '1')) ? 'selected' : '' }}>Hari</option>
                                <option value="2" {{ (isset($satuan_prov) && ($satuan_prov == '2')) ? 'selected' : '' }}>Bulan</option>
                                <option value="3" {{ (isset($satuan_prov) && ($satuan_prov == '3')) ? 'selected' : '' }}>Tahun</option>
                            </select>
                        </div>
                        <label class="col-sm-2 control-label">Satuan Berlaku Luar Provinsi</label>
                        <div class="col-sm-4">
                            <select name="satuan_luar_prov" id="satuan_luar_prov" class="form-control">
                                <option value="">- - Pilih Satuan Berlaku - -</option>
                                <option value="1" {{ (isset($satuan_luar_prov) && ($satuan_luar_prov == '1')) ? 'selected' : '' }}>Hari</option>
                                <option value="2" {{ (isset($satuan_luar_prov) && ($satuan_luar_prov == '2')) ? 'selected' : '' }}>Bulan</option>
                                <option value="3" {{ (isset($satuan_luar_prov) && ($satuan_luar_prov == '3')) ? 'selected' : '' }}>Tahun</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Harga Berlaku Provinsi</label>
                        <div class="col-sm-4">
                            <input type="number" name="harga_prov" id="harga_prov" class="form-control" value="{{ isset($harga_prov) ? $harga_prov : '' }}">                            
                        </div>
                        <label class="col-sm-2 control-label">Harga Berlaku Luar Provinsi</label>
                        <div class="col-sm-4">
                            <input type="number" name="harga_luar_prov" id="harga_luar_prov" class="form-control" value="{{ isset($harga_prov) ? $harga_prov : '' }}">                            
                        </div>
                    </div>                    
                    <hr>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-primary"><i class="fa fa-floppy-o"></i> Simpan</button>
                        </div>
                    </div>
                </form>
            </div><!-- /.box-body -->
        </div><!-- /.box -->
    </div>
</div>
@stop

@section('javascript')
<script type="text/javascript">
    var map;
    var polygon;
    var polygonString = "";
    var polygonCoords = [];

    /**
     * Load Ajax Kabupaten
     */
    function loadComboKabupaten(id_provinsi) {        

        var promise = $.ajax({
            url: "{{ URL::route('provinsis.combo.view.kabupatens') }}",
            type: 'get',            
            data: {
                id_provinsi : id_provinsi
            }
        });

        promise.done(function(data){
            $('#kabupaten_id').html(data);
        });  
    }     

    function loadComboKecamatan(id_kabupaten) {
        var promise = $.ajax({
            url: "{{ URL::route('kabupatens.combo.view.kecamatans') }}",
            type: 'get',            
            data: {
                id_kabupaten : id_kabupaten
            }
        });

        promise.done(function(data){
            $('#kecamatan_id').html(data);
        });  
    }

    function loadComboKelurahan(id_kecamatan) {
        var promise = $.ajax({
            url: "{{ URL::route('kecamatans.combo.view.kelurahans') }}",
            type: 'get',            
            data: {
                id_kecamatan : id_kecamatan
            }
        });

        promise.done(function(data){
            $('#kelurahan_id').html(data);
        });     
    }

    // Convert array polygon into string before submit the form
    function generatePolygonString() {
        var polygonBounds = polygon.getPath();            

        polygonString = "";
        for(var i = 0 ; i < polygonBounds.length ; i++)
        {
            polygonString += polygonBounds.getAt(i).lat() + "," + polygonBounds.getAt(i).lng();                
            if(i != polygonBounds.length -1) {
                polygonString += "|";
            }
        }
    }

    // Google map initialize function
    function initialize() {
        var lat = $('#latFld').val();
        var lng = $('#lngFld').val();

        var map_canvas = document.getElementById('map_canvas');
        var map_options = {
            center: new google.maps.LatLng(lat, lng),
            zoom: {{ isset($zoom) ? $zoom : '18';  }},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(map_canvas, map_options);

        /**
         * center change google map event binding
         * update center of google map value
         */
        google.maps.event.addListener(map, 'center_changed', function() {            
            $('#latFld').val( map.getCenter().d );
            $('#lngFld').val( map.getCenter().e );
        });        

        google.maps.event.addListener(map, 'dragend', function() {
            $('#latFld').val( map.getCenter().d );
            $('#lngFld').val( map.getCenter().e );
        });        

        /**
         * Drawing manager init
         * enable polygon mode on drawing manager
         */
        var drawingManager = new google.maps.drawing.DrawingManager({            
            drawingControl: true,
            drawingControlOptions: {
                position: google.maps.ControlPosition.TOP_CENTER,
                drawingModes: [                    
                    google.maps.drawing.OverlayType.POLYGON,                    
                ]
            },  
            circleOptions: {
                fillColor: '#ffff00',
                fillOpacity: 1,
                strokeWeight: 5,
                clickable: false,
                zIndex: 1,
                editable: true
            }
        });
        drawingManager.setMap(map);

        /**
         * On polygon complete event binding
         * generate polygon string before save into database         
         */
        google.maps.event.addListener(drawingManager, 'polygoncomplete', function(data) {                                     
            // set editable polygon               
            polygon = data;
            polygon.setEditable(true);            
            drawingManager.setMap(null);           
            generatePolygonString();                     
        });

        /**
         * Create the polygon if exists         
         */
        var promise = $.getJSON("{{ URL::route('lingkungan.get.polygon.json') }}");

        promise.done(function(coordinates){     

            /**
             * Pushing into polygon coordinates array
             */
            for (var key in coordinates) {                
                var lat_lng = coordinates[key];
                polygonCoords.push(new google.maps.LatLng(lat_lng.lat, lat_lng.lng));
            }

            /**
             * If polygon exist then draw it
             */
            if(polygonCoords.length > 0) {
                // Construct the polygon.
                polygon = new google.maps.Polygon({
                    paths: polygonCoords,                                        
                    editable: true            
                });
                var polygonBounds = polygon.getPath();             
                
                // generate polygonString
                generatePolygonString();
                polygon.setMap(map);
                drawingManager.setMap(null);     

                /**
                 * Generate polygon string on every insert and set polygon
                 * make sure the polygon string is always update                 
                 */
                google.maps.event.addListener(polygon.getPath(), 'insert_at', function(index, obj) {
                    generatePolygonString(); 
                    // set editable polygon
                    polygon.setEditable(true);            
                    drawingManager.setMap(null);                    
                });
                google.maps.event.addListener(polygon.getPath(), 'set_at', function(index, obj) {
                    generatePolygonString();
                    // set editable polygon
                    polygon.setEditable(true);            
                    drawingManager.setMap(null);                    
                });               
            }            
        });        
    }

    // Init google map
    google.maps.event.addDomListener(window, 'load', initialize);    

    $(document).ready(function() {                            

        /**
         * Combo 
         */        
        
        $('#provinsi_id').change(function(event) {
            event.preventDefault();            

            if($(this).val() != "") {
                loadComboKabupaten($(this).val());
                $('#kabupaten_id').prop('disabled', false);
            }else{
                $('#kabupaten_id').val("");                
                $('#kabupaten_id').prop('disabled', 'disabled');                
                $('#kabupaten_id').trigger('change');
                $('#kelurahan_id').val("");
                $('#kelurahan_id').prop('disabled', 'disabled');                                
            }            
        });        
        $('#provinsi_id').trigger('change');        

        $('#kabupaten_id').change(function(event) {
            event.preventDefault();

           if($(this).val() != "") {
                loadComboKecamatan($(this).val());
                $('#kecamatan_id').prop('disabled', false);                
            }else{
                $('#kecamatan_id').val("");
                $('#kecamatan_id').prop('disabled', 'disabled');                                
                $('#kelurahan_id').val("");
                $('#kelurahan_id').prop('disabled', 'disabled');                                
            } 
        });              
        $('#kabupaten_id').trigger('change');

        $('#kecamatan_id').change(function(event) {
            event.preventDefault();

            if($(this).val() != "") {
                loadComboKelurahan($(this).val());
                $('#kelurahan_id').prop('disabled', false);
            }else{
                $('#kelurahan_id').val("");
                $('#kelurahan_id').prop('disabled', 'disabled');                
            }
        });        
        $('#kecamatan_id').trigger('change');

        // Form submit
        $('#frmInput').submit(function(event) {
            event.preventDefault();

            /**
             * Get each variable value             
             */
            var lat            = $('#latFld').val();
            var lng            = $('#lngFld').val();
            var lat_lng        = lat + "|" + lng;
            var polygon        = polygonString;
            var logo_kop_surat = $('.img-logo').data('filename');            
            var using_kepling  = 0;
            var using_keldat   = 0;
            var ttd_kepling    = $('.img-ttd-kepling').data('filename');            
            var ttd_keldat     = $('.img-ttd-keldat').data('filename');                        

            if($('#using_kepling').is(':checked')) {
                using_kepling = 1;                
            }                
            if($('#using_keldat').is(':checked')) {
                using_keldat = 1;
            }

            /**
             * Generate form data for ajax submit                        
             */
            var formData = $(this).serialize() + "&logo_kop_surat=" + logo_kop_surat;
            formData += "&ttd_kepling=" + ttd_kepling;
            formData += "&ttd_keldat=" + ttd_keldat;
            formData += "&zoom=" + map.getZoom();
            formData += "&lat_lng=" + lat_lng;
            formData += "&polygon=" + polygon;
            formData += "&using_kepling=" + using_kepling;
            formData += "&using_keldat=" + using_keldat;

            bootbox.confirm('Yakin simpan data lingkungan ?', function(yes) {
                if(yes) {
                    var notice = new PNotify({
                        text: "Sedang mengupdate...",
                        type: "info",
                        shadow: false,
                        opacity: .8
                    });

                    $.ajax({
                        url: "{{ URL::route('lingkungan.update') }}",
                        type: 'post',
                        data: formData,
                        success: function(data) {
                            var options = {
                                text: data.msg,
                                type: data.type
                            };
                            notice.update(options);
                        }
                    });

                }
            });

        });

        /*
         * Upload Logo Lingkungan
         */
        $('.btn-upload-logo').click(function(event) {
            event.preventDefault();
            $('#logo').click();
        });

        $('#logo').change(function(event) {
            event.preventDefault();

            var current = $(this);
            var notice = new PNotify({
                text: "Upload logo",
                type: "info",
                shadow: false,
                opacity: .8
            });

            // Generate Form Data
            var formData = new FormData();
            formData.append("logo", $(this)[0].files[0]);

            $.ajax({
                url: "{{ URL::route('lingkungan.upload.logo') }}",
                type: 'post',
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {

                    if(data.type == "success") {
                        $(current).prev().find('img').attr('src', data.full_filename);
                        $(current).prev().find('img').attr('data-filename', data.filename);
                        var options = {
                            text: "Uploaded successfully",
                            type: data.type
                        };
                    }else{
                        var options = {
                            text: data.msg,
                            type: data.type
                        };
                    }
                    notice.update(options);
                }
            });

        });

        /**
         * Upload TTD Kepala Lingkungan
         */
        $('.btn-upload-ttd-kepling').click(function(event) {
            event.preventDefault();
            $('#ttd_kepling').click();
        });

        $('#ttd_kepling').change(function(event) {
            event.preventDefault();

            var current = $(this);
            var notice = new PNotify({
                text: "Upload TTD Kepala Lingkungan",
                type: "info",
                shadow: false,
                opacity: .8
            });

            // Generate Form Data
            var formData = new FormData();
            formData.append("ttd_kepling", $(this)[0].files[0]);

            $.ajax({
                url: "{{ URL::route('lingkungan.upload.ttd.kepling') }}",
                type: 'post',
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {

                    if(data.type == "success") {
                        $(current).prev().find('img').attr('src', data.full_filename);
                        $(current).prev().find('img').attr('data-filename', data.filename);
                        var options = {
                            text: "Uploaded successfully",
                            type: data.type
                        };
                    }else{
                        var options = {
                            text: data.msg,
                            type: data.type
                        };
                    }
                    notice.update(options);
                }
            });
        });

        /**
         * Upload TTD Kelian Adat
         */
        $('.btn-upload-ttd-keldat').click(function(event) {
            event.preventDefault();
            $('#ttd_keldat').click();
        });        

        $('#ttd_keldat').change(function(event) {
            event.preventDefault();

            var current = $(this);
            var notice = new PNotify({
                text: "Upload TTD Kelian Adat",
                type: "info",
                shadow: false,
                opacity: .8
            });

            // Generate Form Data
            var formData = new FormData();
            formData.append("ttd_keldat", $(this)[0].files[0]);

            $.ajax({
                url: "{{ URL::route('lingkungan.upload.ttd.keldat') }}",
                type: 'post',
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {

                    if(data.type == "success") {
                        $(current).prev().find('img').attr('src', data.full_filename);
                        $(current).prev().find('img').attr('data-filename', data.filename);
                        var options = {
                            text: "Uploaded successfully",
                            type: data.type
                        };
                    }else{
                        var options = {
                            text: data.msg,
                            type: data.type
                        };
                    }
                    notice.update(options);
                }
            });
        });
    });
</script>
@stop